package com.ricky.mq.client.code.manager;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ricky.mq.client.code.constant.ClientCommandCode;
import com.ricky.mq.client.code.handler.WaitOrSendMsgHandler;
import com.ricky.mq.client.connection.ClientConnection;
import com.ricky.mq.client.message.data.CallbackData;
import com.ricky.mq.client.message.data.client.ClientHeartbeatCheckData;
import com.ricky.mq.client.message.data.server.ServerHeartbeatCheckData;

/**
 * 心跳检查类
 *
 * @author ricky
 * @since 2020.06.18
 */
public class HeartbeatCheckManager implements Runnable {

    private static int timeOutCount = 0;

    /**
     * 记日志的
     */
    private static Log LOG = LogFactory.get(HeartbeatCheckManager.class);

    @Override
    public void run() {
        ClientConnection connection = ClientConnection.getClientConnection();
        // 如果连接断开，就不断的尝试连接。
        if (connection.isDisconnected()) {
            connection.connection();
        } else {
            CallbackData callbackData =WaitOrSendMsgHandler.syncSendData(ClientCommandCode.HEART_BEAT_CHECK, ClientHeartbeatCheckData.build().setUuid(IdUtil.fastSimpleUUID()));
            if (!callbackData.isSuccess() || !Convert.convert(ServerHeartbeatCheckData.class, callbackData.getBaseData()).isSuccess()) {
                timeOutCount++;
            }

            if (callbackData.isSuccess()) {
                ServerHeartbeatCheckData s = Convert.convert(ServerHeartbeatCheckData.class, callbackData.getBaseData());
                if (s.isSuccess()) {
                    LOG.debug("与服务端心跳检查正常。");
                    timeOutCount = 0;
                } else {
                    timeOutCount++;
                }
            }

            if (timeOutCount >= 3) {
                LOG.error("与服务端的通道虽保持连接，但与服务器之间的心跳检测无响应！无响应次数：" + timeOutCount);
            }
        }
    }
}
